#!/usr/bin/env node

const http=require('http'),
      url=require('url'),
      qs=require('querystring'),
      log=console.log;

let items=[];

http.createServer((req,res)=>{
  let path=url.parse(req.url).pathname;

  if(path!='/'){
    res.statusCode=404;
    res.setHeader('Content-Length',mes.length);
    res.serHeader('Content-Type','text/plain');

    res.end('Not Found!');
  }
  
  log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
  log(req.headers);
  log('');

  //添加列表项
  add(req,res);

}).listen(8080);


function add(req,res){
  const value=qs.parse(url.parse(req.url).query).item;
  if(typeof value!=='undefined'&&value!==''){
    items.push(value);
  }

  log(items);
  showHtml(res);
}



function showHtml(res){
  let html=`
  <!DOCTYPE html>
  <html>
    <head>
      <meta charset='utf8'/>
      <title>todolist</title>
    </head>
    <body>
      <h1>Todolist</h1>
      <form method='get' action='/'>
        <input type='text' name='item' />
        <input type='submit' value='addItem' />
      </form>
      <ul>
        ${items.map(item=>'<li>'+item+'</li>').join('\n')}
      </ul>
    </body>
  </html>`;

  res.setHeader('Content-Type','text/html');
  res.setHeader('Content-Length',Buffer.byteLength(html));
  
  res.statusCode=200;
  res.end(html);

}
